package net.vkits.controller;

import net.vkits.anjiamiao.application.CustomerApplicationService;
import net.vkits.anjiamiao.domain.model.Customer;
import net.vkits.common.Utils;
import net.vkits.common.storage.StorageService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Optional;


/**
 * Created by ethan-liu on 16/4/6.
 */
@Controller
@RequestMapping("/customers")
public class CustomerController {
    private static final Logger log = LoggerFactory.getLogger(CustomerController.class);

    @Resource
    CustomerApplicationService customerApplicationService;
    @Resource
    StorageService storageService;

    @RequiresPermissions("customers:view")
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView customers() {
        String username = Utils.getUsername(SecurityUtils.getSubject()).orElse("Null");
        ModelMap modelMap = new ModelMap();
        modelMap.put("treeview", "customer");
        modelMap.put("sidebar", "customers");
        modelMap.put("currentUser",username);
        return new ModelAndView("/customers", modelMap);
    }

    @RequiresPermissions("customers:view")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ResponseBody
    public Page<Customer> getCustomers(@PageableDefault(value = 10, sort = {"id"}, direction = Sort.Direction.DESC)Pageable pageable) {
        Page<Customer> customers = customerApplicationService.getCustomers(pageable);
        log.info("size is: {}", customers.getTotalElements());
        return customers;
    }

    @RequiresPermissions("customers:modify")
    @RequestMapping(value ="/{cellPhoneNum}", method = RequestMethod.GET)
    public ModelAndView customer(@PathVariable String cellPhoneNum) {
        log.info("cellPhoneNum: {}", cellPhoneNum);
        String username = Utils.getUsername(SecurityUtils.getSubject()).orElse("Null");
        Optional<Customer> customerOptional = customerApplicationService.getCustomer(cellPhoneNum);
        ModelMap modelMap = new ModelMap();
        customerOptional.ifPresent(customer -> modelMap.put("customer", customer));
        modelMap.put("treeview", "customer");
        modelMap.put("sidebar", "customers");
        modelMap.put("currentUser", username);
        return new ModelAndView("/customer", modelMap);
    }

    @RequiresPermissions("customers:modify")
    @RequestMapping(value ="/update", method = RequestMethod.POST)
    public String contractUpdate(@RequestParam(value = "cellPhoneNum", required = true) String cellPhoneNum,
                                 @RequestParam(value = "isVIP", required = true) boolean isVIP,
                                 @RequestParam(value = "isBlock", required = true) boolean isBlock,
                                 @RequestParam(value = "status", required = true) String status) {
        customerApplicationService.changeAuthenticationStatus(cellPhoneNum,status,isVIP,isBlock);
        return "redirect:/customers";
    }

    @RequestMapping(value = "files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<org.springframework.core.io.Resource> serveFile(@PathVariable String filename) {
        org.springframework.core.io.Resource file = storageService.loadAsResource(filename);
        return ResponseEntity
                .ok()
//                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+file.getFilename()+"\"")
                .contentType(MediaType.IMAGE_JPEG)
                .body(file);
    }
}
